<template>
  <div class="lix-auth">
    <div class="lix-auth__img">
      <image class="lix-auth__img" src="../../static/image/logo.png" />
    </div>
    <!-- <p>使用小程序授权登录，我们需要您的用户信息来设置默认的头像、昵称</p> -->
    <button v-if="canIUse" open-type="getUserInfo" @getuserinfo="bindGetUserInfo">小程序授权登录</button>
  </div>
</template>

<script>
import { USER_SET_INFO } from '../../store/mutation-types';
import { mapGetters, mapActions } from 'vuex';
import Tip from '../../utils/tips';

export default {
  computed: {
    ...mapGetters('user', {
      name: 'realname'
    })
  },
  data() {
    return {
      canIUse: wx.canIUse('button.open-type.getUserInfo')
    };
  },
  onLoad() {
    this.check();
  },
  methods: {
    check() {
      const self = this;
      // 查看是否授权
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userInfo']) {
            console.log('已经授权');
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
              success: function(res) {
                console.log(res.userInfo);
                const nickname = res.userInfo.nickName;
                const avatar = res.userInfo.avatarUrl;
                self.changeAvatar(nickname, avatar);
              }
            });
          } else {
            console.log('没有授权');
          }
        }
      });
    },
    ...mapActions('user', {
      'changeUserInfo': USER_SET_INFO
    }),
    // 将微信的头像和昵称上传
    changeAvatar(nickname, avatar) {
      this.changeUserInfo({
        params: {
          'nickname': nickname,
          'avatar': avatar
        },
        callback: function() {
          Tip.success('授权成功')
            .then(res => {
              wx.navigateBack();
            });
        }
      });
    },
    bindGetUserInfo(e) {
      // console.log(e.detail.userInfo);
      console.log(e);
      const nickname = e.mp.detail.userInfo.nickName;
      const avatar = e.mp.detail.userInfo.avatarUrl;
      this.changeAvatar(nickname, avatar);
    }
  }
};
</script>

<style lang="scss">
  @import "../../theme-chalk/auth.scss";
</style>
